package com.banmao.util;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.LinkedList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 幂等工具
 */
public class IdempotentUtil {

    private static final Cache<String, Integer> cache = CacheBuilder.newBuilder()
            .maximumSize(10)
            .expireAfterWrite(5, TimeUnit.SECONDS)
            .build();

    public static boolean lock(KeyParam keyParam) throws ExecutionException {

        LinkedList<Object> keyList = keyParam.keyList;
        if (keyList.isEmpty()) {
            throw new IllegalStateException("keyParam has no param");
        }

        StringBuilder sb = new StringBuilder();
        for (Object key : keyList) {
            sb.append(key);
        }

        Integer i = cache.get(sb.toString(), () -> -999);
        if (i == -999) {
            cache.put(sb.toString(), 1);
        } else {
            return false;
        }
        return true;
    }

    public static class KeyParam {

        private final LinkedList<Object> keyList = new LinkedList<>();

        private KeyParam() {}

        public static KeyParam builder() {
            return new KeyParam();
        }

        public KeyParam putCtx(Object key) {
            keyList.add(key);
            return this;
        }

    }


}
